﻿using com.uplus.log4net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
    /// 
    [ReActionFilter]
    public class FileUploadController : BaseController
    {

        #region 文件上传
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        [DisableRequestSizeLimit]
        public IActionResult FileSave(List<IFormFile> files)
        {
            List<string> listSuffix = new List<string>();
            listSuffix.Add("jpg");
            listSuffix.Add("jpeg");
            listSuffix.Add("bmp");
            listSuffix.Add("png");
            listSuffix.Add("avi");
            listSuffix.Add("mpg");
            listSuffix.Add("mp4");
            listSuffix.Add("mpeg");
            listSuffix.Add("wmv");
            listSuffix.Add("ob");
            listSuffix.Add("mkv");
            listSuffix.Add("mov");
            listSuffix.Add("rmvb");
            listSuffix.Add("mp3");
            listSuffix.Add("wma");
            listSuffix.Add("zip");
            listSuffix.Add("pdf");
            listSuffix.Add("pptx");
            listSuffix.Add("ppt");
            listSuffix.Add("doc");
            listSuffix.Add("docx");
            listSuffix.Add("xlsx");
            listSuffix.Add("xls");
            ResponseDataFile res = new ResponseDataFile();
            string webRootPath = ServiceBase.Get<HostingEnvironment>().WebRootPath;
            string contentRootPath = ServiceBase.Get<HostingEnvironment>().ContentRootPath;
            long size = 0;
            JObject jo = new JObject();
            try
            {
                foreach (var file in files)
                {
                    byte[] buffer = Guid.NewGuid().ToByteArray();
                    int iSeed = BitConverter.ToInt32(buffer, 0);
                    Random random = new Random(iSeed);
                    Thread.Sleep(random.Next(1, 300));
                    string fileName = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                   .FileName
                                   .Trim('"');
                    string suffix = fileName.Substring(fileName.LastIndexOf('.') + 1);
                    string fName = "";
                    string newName = "";

                    if (!listSuffix.Contains(suffix.ToLower()))
                    {
                        res.code = 202;
                        res.msg = string.Format("系统异常");
                        res.file = "";
                        return new JsonResult(res);
                    }
                    if (suffix != "zip")
                    {
                        fName = string.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now);
                        newName = string.Format(fName + ".{0}", suffix);
                    }
                    else
                    {
                        newName = fileName;
                    }

                    string path = $"{webRootPath}{Path.DirectorySeparatorChar}Data{Path.DirectorySeparatorChar}{newName}";
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    size += file.Length;
                    using (FileStream fs = System.IO.File.Create(path))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    jo.Add("code", 0);
                    jo.Add("originalName", fileName);
                    jo.Add("msg", string.Format("上传成功"));
                    jo.Add("fileName", newName);
                    res.code = 200;
                    res.msg = string.Format("上传成功");
                    res.file = newName;
                }
            }
            catch (Exception ex)
            {
                Log4Helper.Error("文件上传", ex.ToString());
                res.code = 202;
                res.msg = string.Format("上传失败");
                res.file = "";
            }
            return new JsonResult(res);
        }
        #endregion

        #region 批量上传

        /// <summary>
        ///   
        /// </summary>
        [HttpPost]
        [DisableRequestSizeLimit]
        public IActionResult FileBatchUpload(List<IFormFile> files, IFormCollection fkMagazine)
        {
            ResponseData res = new ResponseData();
            ModelData modelData = new ModelData();
            string webRootPath = ServiceBase.Get<HostingEnvironment>().WebRootPath;
            string contentRootPath = ServiceBase.Get<HostingEnvironment>().ContentRootPath;
            long size = 0;
            JObject jo = new JObject();
            if (!this.Identification(out res))
            {
                return new JsonResult(res);
            }
            try
            {
                foreach (var file in files)
                {
                    string fileName = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                   .FileName
                                   .Trim('"');
                    string suffix = fileName.Substring(fileName.LastIndexOf('.') + 1);
                    string fName = "";
                    string newName = "";
                    if (suffix != "zip")
                    {
                        fName = fName = $"{ DateTime.Now.ToString("yyyyMMddHHmmssfff")}";
                        newName = string.Format(fName + ".{0}", suffix);
                    }
                    else
                    {
                        newName = fileName;
                    }
                    //string newName = string.Format("{0:yyyyMMddHHmmssfff}.{1}", DateTime.Now, suffix);

                    string path = $"{webRootPath}{Path.DirectorySeparatorChar}Data{Path.DirectorySeparatorChar}{newName}";
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                    string targetPath = $"{webRootPath}{Path.DirectorySeparatorChar}Data{Path.DirectorySeparatorChar}{fName}.PDF";
                    size += file.Length;
                    using (FileStream fs = System.IO.File.Create(path))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    jo.Add("code", 0);
                    jo.Add("originalName", fileName);
                    jo.Add("msg", string.Format("上传成功"));
                    jo.Add("fileName", newName);
                    res.ErrorCode = 0;
                    res.Message = string.Format("上传成功");
                    modelData.TotalPage = 0;
                    modelData.DataList = jo;
                    res.DataList = modelData;
                }
            }
            catch (Exception ex)
            {
                res.ErrorCode = 1;
                res.Message = string.Format("上传失败");
                res.DataList = modelData;
            }
            return new JsonResult(res);

        }

        #endregion

        #region 文件上传
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        [DisableRequestSizeLimit]
        public IActionResult FileSave2([FromQuery] IFormFile files)
        {
            List<string> listSuffix = new List<string>();
            listSuffix.Add("jpg");
            listSuffix.Add("jpeg");
            listSuffix.Add("bmp");
            listSuffix.Add("png");
            listSuffix.Add("avi");
            listSuffix.Add("mpg");
            listSuffix.Add("mp4");
            listSuffix.Add("mpeg");
            listSuffix.Add("wmv");
            listSuffix.Add("ob");
            listSuffix.Add("mkv");
            listSuffix.Add("mov");
            listSuffix.Add("rmvb");
            listSuffix.Add("mp3");
            listSuffix.Add("wma");
            listSuffix.Add("zip");
            listSuffix.Add("pdf");
            listSuffix.Add("pptx");
            listSuffix.Add("ppt");
            listSuffix.Add("doc");
            listSuffix.Add("docx");
            listSuffix.Add("xlsx");
            listSuffix.Add("xls");
            ResponseDataFile res = new ResponseDataFile();
            string webRootPath = ServiceBase.Get<HostingEnvironment>().WebRootPath;
            string contentRootPath = ServiceBase.Get<HostingEnvironment>().ContentRootPath;
            long size = 0;
            JObject jo = new JObject();
            try
            {
                if (files != null)
                {
                    string fName = "";
                    string newName = "";
                    string path = $"{webRootPath}{Path.DirectorySeparatorChar}Data{Path.DirectorySeparatorChar}";
                    var fileDir = $"{webRootPath}{Path.DirectorySeparatorChar}Data";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    //文件名称 
                    string suffix = files.FileName.Substring(files.FileName.LastIndexOf('.') + 1);
                    
                    fName = string.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now);
                    newName = string.Format(fName + ".{0}", suffix);
                    //上传的文件的路径
                    string filePath = $"{webRootPath}{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}{newName}";
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        files.CopyTo(fs);
                        fs.Flush();
                    }
                    fName = string.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now);
                    jo.Add("originalName", files.FileName);
                    jo.Add("msg", string.Format("上传成功"));
                    jo.Add("fileName", newName);
                    res.code = 200;
                    res.msg = string.Format("上传成功");
                    res.file = newName;
                }

            }
            catch (Exception ex)
            {
                Log4Helper.Error("文件上传", ex.ToString());
                res.code = 202;
                res.msg = string.Format("上传失败");
                res.file = "";
            }
            return new JsonResult(res);
        }
        #endregion

    }
}
